package jwtutils


import (
"fmt"
"github.com/golang-jwt/jwt"
"time"
)
var hmacSampleSecret = []byte("myjwt2secret")

func SetSecret(secret string)  {
	hmacSampleSecret = []byte(secret)
}

func getSecret() []byte {
	return hmacSampleSecret
}

/**
为了方便，加了两个常用字段，一个int64,一个string
不用，就不用赋值
MapVal要用WithClaim，因为有可能没有初始化
 */
type MyClaims struct {
	UserId int64 `json:"i,omitempty"`
	SVal string `json:"s,omitempty"`
	MapVal map[string]interface{} `json:"m,omitempty"`
	jwt.StandardClaims
}

func NewMyClaims() *MyClaims {
	return &MyClaims{}
}
/**
以秒为单位设置过期时间
*/
func (c *MyClaims)ExpAt(s time.Duration) *MyClaims {
	c.ExpiresAt = time.Now().Add(s).Unix()
	return c
}
func (c *MyClaims)SetId(id int64) *MyClaims {
	c.UserId = id
	return c
}
func (c *MyClaims)SetString(s string) *MyClaims {
	c.SVal = s
	return c
}
func (c *MyClaims)ReleaseToken() (string,error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	return token.SignedString(getSecret())
}

func (c *MyClaims)WithClaim(key string,val interface{})  *MyClaims  {
	if c.MapVal == nil {
		c.MapVal = make(map[string]interface{})
	}
	c.MapVal[key] = val
	return c
}



func NewJwtMapClaims(tokenString string) (jwt.MapClaims,error)  {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		// Don't forget to validate the alg is what you expect:
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}

		// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
		return []byte(hmacSampleSecret), nil
	})
	//fmt.Println(token.Claims)
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims,nil
	} else {
		return nil,err
	}
}


